$(document).ready(function() {
    const searchInput = $('#searchInput');
    const suggestions = $('#suggestions');
    const resultsBody = $('#resultsBody');

    searchInput.on('input', function() {
        const query = $(this).val().trim();
        
        if(query.length > 0) {
            $.get('/search', { q: query }, function(data) {
                suggestions.empty().show();
                data.forEach(item => {
                    suggestions.append(
                        `<div class="list-group-item" data-code="${item.code}">
                            ${item.name.replace(new RegExp(query, 'gi'), match => `<mark>${match}</mark>`)}
                        </div>`
                    );
                });

                // 点击建议项填充搜索框
                $('.list-group-item').on('click', function() {
                    searchInput.val($(this).text().replace(/<[^>]*>/g, ''));
                    suggestions.hide();
                    updateResults($(this).data('code'));
                });
            });
        } else {
            suggestions.hide();
            resultsBody.empty();
        }
    });

    function updateResults(selectedCode) {
        $.get('/search', { q: searchInput.val().trim() }, function(data) {
            resultsBody.empty();
            if(data.length === 0) {
                resultsBody.append(`<tr><td colspan="2" class="text-muted">未找到相关物品代码</td></tr>`);
            }
            data.filter(item => item.code === selectedCode).forEach(item => {
                resultsBody.append(
                    `<tr>
                        <td>${item.name}</td>
                        <td><code>${item.code}</code></td>
                    </tr>`
                );
            });
        });
    }

    function loadHotList() {
        $.get('/hot10', function(data) {
            $('#hotList').empty();
            data.forEach(item => {
                $('#hotList').append(
                    `<li class="list-group-item d-flex justify-content-between align-items-center">
                        ${item.name}
                        <span class="badge bg-primary rounded-pill">${item.count}</span>
                    </li>`
                );
            });
        });
    }
});